import hashlib
import json
from urllib import request as url_req
from xml.etree import ElementTree as ET
from flask import Flask, request, make_response
import re
import redis
import time

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World! ww'


'''
成绩查询接口
/student/info/{code}
'''


@app.route('/achievement', methods=['GET', 'POST'])
def get_achievement():
    if request.method == 'POST':
        xml_recv = ET.fromstring(request.data)
        fromUserName = xml_recv.find('FromUserName').text
        toUserName = xml_recv.find('ToUserName').text
        code = get_from_redis(fromUserName)
        reply = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"
        with url_req.urlopen('http://hdu.sunnysport.org.cn/api/student/info/' + code) as f:
            info = json.loads(f.read().decode('utf-8'))
            response = make_response(reply % (fromUserName, toUserName, str(int(time.time())), info['validTimes']))
            response.content_type = 'application/xml'
            return response


@app.route('/user', methods=['GET', 'POST'])
def user():
    # 先进行身份验证
    if request.method == 'GET':
        echostr = validate_user(request)
        if echostr is not None:
            return make_response(echostr)
    # 读取xml数据
    else:
        xml_recv = ET.fromstring(request.data)
        toUserName = xml_recv.find('ToUserName').text
        fromUserName = xml_recv.find('FromUserName').text
        content = xml_recv.find('Content').text
        if content.startswith('绑定'):
            return save_user(fromUserName=fromUserName, toUserName=toUserName, content=content)


def validate_user(request):
    token = ''
    data = request.args
    signature = data.get('signature', '')
    timestamp = data.get('timestamp', '')
    nonce = data.get('nonce', '')
    echostr = data.get('echostr', '')
    s = [timestamp, nonce, token]
    s.sort()
    s = ''.join(s)
    if hashlib.sha1(s).hexdigest() == signature:
        return echostr


def save_user(fromUserName, toUserName, content):
    reply = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"
    if save_to_redis(fromUserName=fromUserName, code=re.compile('\d+').search(content).group()):
        print('user' + fromUserName + 'saved')
        response = make_response(reply % (fromUserName, toUserName, str(int(time.time())), "保存成功"))
        response.content_type = 'application/xml'
        return response
    else:
        print('failed to save ' + fromUserName)
        response = make_response(reply % (fromUserName, toUserName, str(int(time.time())), "保存失败"))
        response.content_type = 'application/xml'
        return response


def save_to_redis(fromUserName, code):
    r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
    return r.set(fromUserName, code)


def get_from_redis(key):
    r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
    return r.get(key)


if __name__ == '__main__':
    app.run(port=8000)
